import { defineStore } from 'pinia';
import { login, register, getUserInfo, logout, updateUserInfo, changePassword } from '@/api/user';
import router from '@/router';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    role: localStorage.getItem('userRole') || '',
  }),

  getters: {
    // 获取token
    getToken: (state) => state.token || localStorage.getItem('token'),
    // 是否已登录
    isLoggedIn: (state) => !!state.token || !!localStorage.getItem('token'),
    // 获取角色
    getRole: (state) => state.role || localStorage.getItem('userRole'),
    // 是否是农户
    isFarmer: (state) => state.role === 'farmer' || localStorage.getItem('userRole') === 'farmer',
    // 是否是买家
    isBuyer: (state) => state.role === 'buyer' || localStorage.getItem('userRole') === 'buyer',
    // 是否是卖家
    isSeller: (state) => state.role === 'seller' || localStorage.getItem('userRole') === 'seller',
    // 是否是管理员
    isAdmin: (state) => state.role === 'admin' || localStorage.getItem('userRole') === 'admin',
    // 获取用户名
    userName: (state) => {
      const info = state.userInfo || JSON.parse(localStorage.getItem('userInfo') || '{}');
      return info.nickname || info.username || '';
    }
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        console.log('登录请求参数:', credentials);
        
        // 使用API调用
        const result = await login(credentials);
        console.log('登录响应:', result);
        
        if (!result || !result.success) {
          throw new Error(result.message || '登录失败');
        }
        
        const userData = result.data;
        
        // 保存认证信息
        this.token = userData.token;
        localStorage.setItem('token', userData.token);
        
        // 构建用户信息对象（不包含token）
        const userInfo = {
          id: userData.id,
          username: userData.username,
          nickname: userData.nickname,
          role: userData.role
        };
        
        this.userInfo = userInfo;
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        
        this.role = userData.role;
        localStorage.setItem('userRole', userData.role);
        
        return Promise.resolve(result);
      } catch (error) {
        console.error('登录出错:', error);
        return Promise.reject(error);
      }
    },

    // 注册
    async register(userData) {
      try {
        const result = await register(userData);
        
        if (!result || !result.success) {
          throw new Error(result.message || '注册失败');
        }
        
        // 注册成功但不自动登录，只返回结果
        return Promise.resolve(result);
      } catch (error) {
        console.error('注册出错:', error);
        return Promise.reject(error);
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const result = await getUserInfo();
        
        if (!result || !result.success) {
          throw new Error(result.message || '获取用户信息失败');
        }
        
        // 更新用户信息
        this.userInfo = result.data;
        localStorage.setItem('userInfo', JSON.stringify(result.data));
        
        return Promise.resolve(result);
      } catch (error) {
        console.error('获取用户信息失败:', error);
        return Promise.reject(error);
      }
    },

    // 登出
    async logoutUser() {
      try {
        await logout();
        this.clearUserData();
        router.push('/auth/login');
        return Promise.resolve();
      } catch (error) {
        console.error('登出失败:', error);
        // 即使API调用失败，也清除本地数据
        this.clearUserData();
        router.push('/auth/login');
        return Promise.reject(error);
      }
    },

    // 更新用户信息
    async updateUser(userData) {
      try {
        const result = await updateUserInfo(userData);
        
        if (!result || !result.success) {
          throw new Error(result.message || '更新用户信息失败');
        }
        
        // 更新本地存储的用户信息
        this.userInfo = { ...this.userInfo, ...userData };
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
        
        return Promise.resolve(result);
      } catch (error) {
        console.error('更新用户信息失败:', error);
        return Promise.reject(error);
      }
    },

    // 修改密码
    async updatePassword(passwordData) {
      try {
        const result = await changePassword(passwordData);
        return Promise.resolve(result);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 清除用户数据
    clearUserData() {
      this.token = '';
      this.userInfo = {};
      this.role = '';
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userRole');
    }
  }
}); 